function createXHR() {
    if (typeof XMLHttpRequest != "undefined") {
        return new XMLHttpRequest();
    } else if (typeof ActiveXObject != "undefined") {
        if (typeof arguments.callee.activeXString != "string") {
            var versions = ["MSXML2.XMLHttp.6.0", "MSXML2.XMLHttp.3.0",
                    "MSXML2.XMLHttp"],
                i, len;
            for (i = 0, len = versions.length; i < len; i++) {
                try {
                    new ActiveXObject(versions[i]);
                    arguments.callee.activeXString = versions[i];
                    break;
                } catch (ex) {
                    console.log(ex.textContent);
                }
            }
        }
        return new ActiveXObject(arguments.callee.activeXString);
    } else {
        throw new Error("No XHR object available.");
    }
}

function sendTest() {
    var xhr = createXHR();
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
                alert(xhr.responseText);
            } else {
                alert("Request was unsuccessful: " + xhr.status);
            }
            var myHeader = xhr.getResponseHeader("MyHeader");
            console.log(myHeader);
            var allHeaders = xhr.getAllResponseHeaders();
            console.log(allHeaders);
        }
    };
    xhr.open("get", "../file/example.xml", false);
    xhr.setRequestHeader("MyHeader", "MyValue");
    xhr.send(null);
}

function addURLParam(url, name, value) {
    url += (url.indexOf("?") == -1 ? "?" : "&");
    url += encodeURIComponent(name) + "=" + encodeURIComponent(value);
    return url;
}

function addURLParamTest() {
    var xhr = createXHR();
    var url = "../file/example.xml";
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
                alert(xhr.responseText);
            } else {
                alert("Request was unsuccessful: " + xhr.status);
            }
            var myHeader = xhr.getResponseHeader("MyHeader");
            console.log(myHeader);
            var allHeaders = xhr.getAllResponseHeaders();
            console.log(allHeaders);
        }
    };
    //添加参数
    url = addURLParam(url, "name", "Nicholas");
    url = addURLParam(url, "book", "Professional JavaScript");
    //初始化请求
    xhr.open("get", url, false);
}

function submitData() {
    var xhr = createXHR();
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
                alert(xhr.responseText);
            } else {
                alert("Request was unsuccessful: " + xhr.status);
            }
        }
    };
    xhr.open("post", "../file/example.xml", true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    var form = document.getElementById("user-info");
    xhr.send(serialize(form));
}

function FormDataTest() {
    var xhr = createXHR();
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
                alert(xhr.responseText);
            } else {
                alert("Request was unsuccessful: " + xhr.status);
            }
        }
    };
    xhr.open("post", "../file/example.xml", true);
    var form = document.getElementById("user-info");
    xhr.send(new FormData(form));
}

function ontimeoutTest() {
    var xhr = createXHR();
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            try {
                if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
                    alert(xhr.responseText);
                } else {
                    alert("Request was unsuccessful: " + xhr.status);
                }
            } catch (ex) {
                //假设由ontimeout 事件处理程序处理
                console.log(ex.textContent);
            }
        }
    };
    xhr.open("get", "../file/ljj_xpz.mp3", true);
    xhr.timeout = 10; //将超时设置为10ms
    xhr.ontimeout = function () {
        alert("Request did not return in 10ms.");
    };
    xhr.send(null);
}

function overrideMimeTypeTest() {
    var xhr = createXHR();
    xhr.open("get", "../file/example.xml", true);
    xhr.overrideMimeType("text/xml");
    xhr.send(null);
}

function onloadTest() {
    var xhr = createXHR();
    xhr.onload = function () {
        if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
            console.log(xhr.responseText);
        } else {
            alert("Request was unsuccessful: " + xhr.status);
        }
    };
    xhr.open("get", "../file/example.xml", true);
    xhr.send(null);
}

function onprogressTest() {
    var xhr = createXHR();
    xhr.onload = function (event) {
        if ((xhr.status >= 200 && xhr.status < 300) ||
            xhr.status == 304) {
            // alert(xhr.responseText);
        } else {
            alert("Request was unsuccessful: " + xhr.status);
        }
    };
    xhr.onprogress = function (event) {
        var divStatus = document.getElementById("status");
        if (event.lengthComputable) {
            divStatus.innerHTML = "Received " + event.position + " of " +
                event.totalSize + " bytes";
        }
    };
    xhr.open("get", "../file/ljj_xpz.mp3", true);
    xhr.send(null);
}

function createCORSRequest(method, url) {
    var xhr = new XMLHttpRequest();
    if ("withCredentials" in xhr) {
        xhr.open(method, url, true);
    } else if (typeof XDomainRequest != "undefined") {
        vxhr = new XDomainRequest();
        xhr.open(method, url);
    } else {
        xhr = null;
    }
    return xhr;
}

function createCORSRequestTest() {
    var request = createCORSRequest("get", "http://www.somewhere-else.com/page/");
    if (request) {
        request.onload = function () {
//对request.responseText 进行处理
        };
        request.send();
    }
}

function ImageTest() {
    var img = new Image();
    img.onload = img.onerror = function () {
        alert("Done!");
    };
    img.src = "../file/logo.png";
}

// handleResponse({"ip":"58.215.10.122","country_code":"CN","country_name":"China","region_code":"JS","region_name":"Jiangsu","city":"Wuxi","zip_code":"","time_zone":"Asia/Shanghai","latitude":31.5689,"longitude":120.2886,"metro_code":0});
function handleResponse(response) {
    alert("You’re at IP address " + response.ip + ", which is in " +
        response.city + ", " + response.region_name);
}

//JSONP 是JSON with padding（填充式JSON 或参数式JSON）的简写
function jsonpTest() {
    var script = document.createElement("script");
    script.src = "http://freegeoip.net/json/?callback=handleResponse";
    document.body.insertBefore(script, document.body.firstChild);
}

function createStreamingClient(url, progress, finished) {
    var xhr = new XMLHttpRequest(),
        received = 0;
    xhr.open("get", url, true);
    xhr.onreadystatechange = function () {
        var result;
        if (xhr.readyState == 3) {
            //只取得最新数据并调整计数器
            result = xhr.responseText.substring(received);
            received += result.length;
            //调用progress 回调函数
            progress(result);
        } else if (xhr.readyState == 4) {
            finished(xhr.responseText);
        }
    };
    xhr.send(null);
    return xhr;
}

function createStreamingClientTest() {
    var client = createStreamingClient("../file/example.xml", function (data) {
        // alert("Received: " + data);
    }, function (data) {
        alert("Done!");
    });
}

function EventSourceTest() {
    var source = new EventSource("myevents.php");
    source.onmessage = function (event) {
        var data = event.data;
        //处理数据
    };
    source.close();
}

function WebSocketTest() {
    var socket = new WebSocket("ws://www.example.com/server.php");
    socket.send("Hello world!");
    var message = {
        time: new Date(),
        text: "Hello world!",
        clientId: "asdfp8734rew"
    };
    socket.send(JSON.stringify(message));
    socket.onmessage = function (event) {
        var data = event.data;
        //处理数据
    };

    socket.onopen = function(){
        alert("Connection established.");
    };
    socket.onerror = function(){
        alert("Connection error.");
    };
    socket.onclose = function(){
        alert("Connection closed.");
        console.log("Was clean? " + event.wasClean + " Code=" + event.code + " Reason="
            + event.reason);
    };
}



